package com.lanyou.esb.redis.proxy.impl;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Response;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.lanyou.esb.common.Constants4Redis;
import com.lanyou.esb.redis.JedisPoolUtils;
import com.lanyou.esb.redis.proxy.base.BaseStrJedisProxy;

/**
 * 平台流量分析
 * 
 * @author Davey.wu
 */
@Service
public class QuantityAnalysisJedisProxy extends BaseStrJedisProxy<Long> {
	/** 平台总流量前缀 **/
	public static final String KEYS_SUFFIX = Constants4Redis.PREFIX_INESBTOTALTIME;
	/** 请求响应类型（成功/失败)前缀 **/
	public static final String KEYS_SUFFIX_SF = Constants4Redis.PREFIX_REQRESTYPE;

	public QuantityAnalysisJedisProxy() {
		this.setTimeOut(Constants4Redis.QUANTITY_ANALYSIS_RETENTION_TIME);
	}

	@Override
	public String generateKey(String field) {
		return KEYS_SUFFIX + KEY_SEPARATOR + field;
	}

	@Override
	public String generateKey(String... field) {
		if (field == null) {
			return KEYS_SUFFIX;
		}
		String key = KEYS_SUFFIX;
		for (String str : field) {
			key += KEY_SEPARATOR + str;
		}
		return key;
	}

	@Override
	public String generateKeyFromObject(Long target) {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * 获取请求成功（或失败）键值
	 * 
	 * @param field
	 *            :域
	 * @return
	 */
	public String generateSfKey(String field) {
		return KEYS_SUFFIX_SF + KEY_SEPARATOR + field;
	}

	/**
	 * 获取请求成功（或失败）键值
	 * 
	 * @param fields
	 *            ：域列表
	 * @return
	 */
	public String generateSfKey(String... fields) {
		if (fields == null) {
			return KEYS_SUFFIX_SF;
		}
		String key = KEYS_SUFFIX_SF;
		for (String str : fields) {
			key += KEY_SEPARATOR + str;
		}
		return key;
	}

	@Override
	public Long get(String key) throws JsonParseException,
			JsonMappingException, IOException {
		String value = "";
		Jedis jedis = JedisPoolUtils.getJedis();
		if (jedis == null) {
			return 0l;
		}
		boolean broken = false;
		try {
			value = jedis.get(key);
		} catch (Exception e) {
			broken = true;
		} finally {
			JedisPoolUtils.returnRes(jedis, broken);
		}
		if (StringUtils.isBlank(value)) {
			return 0l;
		}
		try {
			return Long.parseLong(value);
		} catch (Exception e) {
			// 类型错误，默认返回0
			return 0l;
		}
	}

	public Map<String, Long> get(List<String> keys) throws JsonParseException,
			JsonMappingException, IOException {
		if (keys == null || keys.isEmpty()) {
			return null;
		}
		Jedis jedis = JedisPoolUtils.getJedis();
		if (jedis == null) {
			return null;
		}
		boolean broken = false;
		Map<String, Response<String>> map = new HashMap<>(keys.size());
		try {
			Pipeline pipe = jedis.pipelined();
			for (String key : keys) {
				map.put(key, pipe.get(key));
			}
			pipe.sync();
		} catch (Exception e) {
			broken = true;
		} finally {
			JedisPoolUtils.returnRes(jedis, broken);
		}
		if (map.isEmpty()) {
			return null;
		}
		Map<String, Long> result = new HashMap<>(map.size());
		for (Entry<String, Response<String>> entry : map.entrySet()) {
			String value = entry.getValue().get();
			try {
				result.put(entry.getKey(), Long.parseLong(value));
			} catch (Exception e) {
				// 没有值，默认为0
				result.put(entry.getKey(), 0l);
			}
		}
		return result;
	}

	@Override
	public long setex(String key, Long target) throws JsonProcessingException {
		long value = 0;
		if (target != null) {
			value = target.longValue();
		}
		Long result = 0l;
		Jedis jedis = JedisPoolUtils.getJedis();
		if (jedis == null) {
			return 0l;
		}
		boolean broken = false;
		try {
			result = jedis.incrBy(key, value);
		} catch (Exception e) {
			broken = true;
		} finally {
			JedisPoolUtils.returnRes(jedis, broken);
		}
		if (result != null) {
			return result.longValue();
		}
		return 0l;
	}

}
